package org.example.flow.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.flow.domain.*;
import org.example.flow.service.*;
import org.example.flow.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RequestMapping("/flow")
@RestController
public class FlowController {
    @Autowired
    DeptService deptService;
    @Autowired
    FlowService flowService;
    @Autowired
    ProductionService productionService;
    @Autowired
    TflowService tflowService;
    @Autowired
    MarketService marketService;
    @Autowired
    BusinessService businessService;
    @RequestMapping("/list")
    public Result list(Integer pageNum){
        PageHelper.startPage(pageNum,5);
        List<Flow> list = flowService.listall();
        return Result.success(new PageInfo<>(list));
    }
    @RequestMapping("/deptlist")
    public Result deptlist(){
        LambdaQueryWrapper<Dept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dept::getPersonId,2);
        List<Dept> list1 = deptService.list(wrapper);
        return Result.success(list1);
    }
    @Autowired
    RedisTemplate redisTemplate;
    @RequestMapping("/flowadd")
    public Result flowadd(@RequestBody Flow flow){
        Boolean absent = redisTemplate.opsForValue().setIfAbsent(DigestUtil.md5Hex(flow.toString()), "111", 2, TimeUnit.MINUTES);
        if(!absent){
            return Result.fail("请勿重复加工");
        }
        LambdaQueryWrapper<Production> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Production::getId,flow.getProductId());
        Production one = productionService.getOne(wrapper);
        flow.setProductionName(one.getCname());
        flow.setProductionNum(one.getNum());
        flow.setMarketId(one.getMarketId());
        String remarks = Arrays.toString(flow.getRemarks());
        flow.setRemark(remarks);
        String s = IdUtil.getSnowflake().nextIdStr();
        flow.setId(s);
        flow.setStatus("未运输");
        boolean b = flowService.save(flow);
        if(b){
            productionService.removeById(one);
            Tflow tflow = new Tflow();
            tflow.setFId(flow.getId());
            tflow.setFTime(flow.getCreateTime());
            Market market = marketService.getById(flow.getMarketId());
            tflow.setFLongitude(market.getLongitude());
            tflow.setFLatitude(market.getLatitude());
            tflowService.save(tflow);
        }
        return b?Result.success():Result.fail();
    }
}
